package com.tianji.learning.handller;


import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.DateUtils;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsBoard;
import com.tianji.learning.service.IPointsBoardSeasonService;
import com.tianji.learning.service.IPointsBoardService;
import com.tianji.learning.util.TableInfoContext;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@RequiredArgsConstructor
public class PoilerBoartPersistenHandller {

    private final RedisTemplate redisTemplate;

    private final IPointsBoardSeasonService seasonService;

    private final IPointsBoardService pointsBoardService;


    @XxlJob("createTableJob")
    public void creatPointsBoardTableOfLastSeason() {
        //获取上月时间
        LocalDateTime localDateTime = LocalDateTime.now().minusMonths(1);
        //查询赛季id
        Integer seccer = seasonService.querySeaconByTime(localDateTime);
        //赛季不存在
        if (seccer == null) {
            return;
        }
        //创建表
        pointsBoardService.createPointBboardTableByseacon(seccer);
    }


    @XxlJob("savePointBoard2DB")
    public void SavePointsBoard2DB() {
        //获取上月时间
        LocalDateTime localDateTime = LocalDateTime.now().minusMonths(1);

        Integer seccer = seasonService.querySeaconByTime(localDateTime);

        TableInfoContext.setInfo("points_board" + seccer);
        //查询赛季id
        //拼接key
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + localDateTime.format(DateUtils.SIGN_DATE_SUFFIX_FORMATTER);
        //查询数据
        int index = XxlJobHelper.getShardIndex();
        int Total = XxlJobHelper.getShardTotal();
        int pageNo = index + 1;
        int pageSize = 10;
        while (true) {
            List<PointsBoard> list = pointsBoardService.queryCurrentBoardList(key, pageNo, pageSize);
            if (CollUtils.isEmpty(list)) {
                break;
            }
            //把排名信息写入id
            list.forEach(b -> {
                b.setId(b.getUserId().longValue());
                b.setRank(null);
            });
            //持久化到数据库
            pointsBoardService.saveBatch(list);
            //翻页
            pageNo += Total;
        }
    }
    @XxlJob("clearPointsBoardFromRedis")
    public void clearPointsBoardFromRedis() {
        //获取上月时间
        LocalDateTime localDateTime = LocalDateTime.now().minusMonths(1);
        //获取key
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + localDateTime.format(DateUtils.SIGN_DATE_SUFFIX_FORMATTER);
        //删除
        redisTemplate.unlink(key);
    }
}
